package com.inspur.xiaoju.controller;

import com.inspur.xiaoju.common.ApiResponse;
import com.inspur.xiaoju.dto.CreateWorkspaceMemberDto;
import com.inspur.xiaoju.dto.DeleteWorkspaceMemberDto;
import com.inspur.xiaoju.dto.UpdateWorkspaceMemberDto;
import com.inspur.xiaoju.exception.BusinessException;
import com.inspur.xiaoju.model.WorkspaceMember;
import com.inspur.xiaoju.service.WorkspaceMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;  // 添加这个导入
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/workspace-members")
public class WorkspaceMemberController {

    @Autowired
    private WorkspaceMemberService workspaceMemberService;
    
    @PostMapping
    public ApiResponse<Map<String, String>> create(@Valid @RequestBody CreateWorkspaceMemberDto createDto) {
        WorkspaceMember member = workspaceMemberService.create(createDto);
        // 替换 Map.of() 为 HashMap
        Map<String, String> result = new HashMap<>();
        result.put("memberId", member.getId());
        return ApiResponse.success(result);
    }
    
    @GetMapping
    public ApiResponse<List<WorkspaceMember>> findAll(@RequestParam Map<String, String> params) {
        String workspaceId = params.get("workspaceId");
        if (workspaceId == null || workspaceId.isEmpty()) {
            throw new BusinessException(400, "工作区ID不能为空");
        }
        return ApiResponse.success(workspaceMemberService.findAllByWorkspaceId(workspaceId));
    }
    
    @PutMapping("/role")
    public ApiResponse<Map<String, Object>> updateRole(@Valid @RequestBody UpdateWorkspaceMemberDto updateDto,
                                                      @RequestAttribute("userId") String userId,
                                                      @RequestAttribute("username") String username) {
        return ApiResponse.success(workspaceMemberService.updateRole(updateDto, username, userId));
    }
    
    @DeleteMapping
    public ApiResponse<Map<String, Object>> delete(@Valid @RequestBody DeleteWorkspaceMemberDto deleteDto) {
        return ApiResponse.success(workspaceMemberService.deleteMember(deleteDto));
    }
}